package com.test.system.admin.shiro;

import com.test.system.admin.dao.AdminUserDAO;
import com.test.system.admin.dao.PermDao;
import com.test.system.admin.pojo.AdminUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author 徒有琴
 */
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    private AdminUserDAO adminUserDAO;
    @Autowired
    private PermDao permDao;

    //进行权限验证的时候，获取用户权限的
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("doGetAuthorizationInfo");
        int userId = (int) principalCollection.getPrimaryPrincipal();//登录时存的唯一标识
        //查询用户角色表，获得用户的角色信息，假设查出来的是admin
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        List<Integer> roleIds=permDao.getUserRoleIds(userId);//查询出用户所有的角色
        for (Integer roleId : roleIds) {
            info.addRole(roleId.toString());
        }
        List<String> perms=permDao.getUserPermission(userId);//查询用户权限
        info.addStringPermissions(perms);
        //info.addRole("admin");
        return info;
    }

    //Subject.login  登陆的时候会执行这个方法
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        String username = token.getUsername();
        //查询数据库
        AdminUser user = adminUserDAO.getUserByEmail(username);
        if (user == null) {
            return null;
        }
        //当前用户的唯一标识 （主键），用户在数据库中的密码，当前realm的名字
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
        return info;
    }
}
